package com.lujianfei.preference;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public static class SettingsFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        EditTextPreference editTextPreference;
        CheckBoxPreference checkBoxPreference;
        ListPreference listPreference;
        MultiSelectListPreference multiSelectListPreference;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settingsfragment);

            editTextPreference = (EditTextPreference) findPreference("editTextPreference");
            checkBoxPreference = (CheckBoxPreference) findPreference("checkBoxPreference");
            listPreference = (ListPreference) findPreference("listPreference");
            multiSelectListPreference = (MultiSelectListPreference) findPreference("multiSelectListPreference");

            editTextPreference.setOnPreferenceChangeListener(this);
            checkBoxPreference.setOnPreferenceChangeListener(this);
            listPreference.setOnPreferenceChangeListener(this);
            multiSelectListPreference.setOnPreferenceChangeListener(this);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference == editTextPreference){
                showToast(""+newValue);
            }
            if (preference == checkBoxPreference){
                showToast(""+newValue);
            }
            if (preference == listPreference){
                showToast(""+newValue);
            }
            if (preference == multiSelectListPreference){
                showToast(""+newValue);
            }
            return true;
        }

        void showToast(String toast){
            Toast.makeText(getContext(),toast,Toast.LENGTH_SHORT).show();
        }
    }
}
